using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Meat.Resources
{
    public interface ICustomResourceType
    {
        void Load(ContentManager content, GraphicsDevice device);
        void Unload();
    }

    public class CustomResource<ResT> : IResource where ResT : class, ICustomResourceType
    {
        bool m_Loaded = false;
        ResT m_Resource;
        ResourceLoader m_Loader;
        String m_Name;

        public String Name
        { get { return m_Name; } }

        public CustomResource(String name, ResT resource)
        {
            m_Resource = resource;
            m_Name = name;
        }

        public void Reset()
        {
            m_Resource.Unload();
            m_Loaded = false;
        }

        public void ForceLoad()
        {
            m_Resource.Load(m_Loader.Content, m_Loader.Device);
            m_Loaded = true;
        }

        public T Get<T>() where T : class
        {
            if (!typeof(T).IsAssignableFrom(typeof(ResT)))
                throw new InvalidOperationException("Tried to get a resource of type " + typeof(ResT).Name + " instead of actual type " + typeof(T).Name);

            if (!m_Loaded)
            {
                ForceLoad();
            }

            return m_Resource as T;
        }


        public void SetLoader(ResourceLoader loader)
        {
            m_Loader = loader;
        }

        public AbstractHandle ToHandle()
        {
            return new Handle<ResT>(m_Name);
        }
    }
}
